package com.example.mq.server;

import com.example.mq.common.*;
import com.example.mq.server.core.BasicProperties;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BrokerServer {
    // 构建一个网卡连接
    private ServerSocket serverSocket = null;
    // 当前只有一个虚拟主机，待扩展
    private VirtualHost virtualHost = new VirtualHost("default");
    // 当前的key为channelId，一个tcp连接下有多个channel
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    // 使用线程池来接受多个客户端的请求
    private ExecutorService executorService = null;
    // 用于手动停止服务器
    private volatile boolean runnable = true;

    // 开通一个端口
    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    // 服务器正式启动
    public void start() throws IOException {
        System.out.println("[BrokerServer] 服务器启动！");
        // 创建线程池 这个线程池没有线程上限
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                // 获取客户端连接
                Socket clientSocket = serverSocket.accept();
                // 由线程池处理客户端发送的请求
                executorService.submit(()->{
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器停止！");
        }
    }

    public void stop() throws IOException {
        runnable = false;
        executorService.shutdownNow();
        serverSocket.close();
    }

    // 这个方法用于处理一个客户端连接
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            // 这里需要按照特定的格式解析
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while(true) {
                    // 1.读取请求并解析
                    Request request = readRequest(dataInputStream);
                    // 2.根据请求计算响应
                    Response response = process(request, clientSocket);
                    // 3.将响应返回给客户端
                    writeResponse(dataOutputStream, response);
                }
            }
        } catch (EOFException | SocketException e) {
            System.out.println("[BrokerServer] connection 关闭！客户端地址：" + clientSocket.getInetAddress().toString()
                + "：" + clientSocket.getPort());
        } catch (IOException | ClassNotFoundException | MqException e) {
            System.out.println("[BrokerServer] connection出现异常！");
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 读取请求并解析
    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        // 将读取到的类型写入请求
        request.setType(dataInputStream.readInt());
        // 将内容的长度写入请求
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("读取请求格式失败！");
        }
        request.setPayload(payload);
        return request;
    }

    // 根据请求计算响应
    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 1.先将 request 中的 payload 做一个初步的解析
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        System.out.println("type = "+request.getType() + ",length = " + request.getLength()
                + "[Request] rid = " +basicArguments.getRid() + ",channelId = " +basicArguments.getChannelId());
        // 2.根据type的值，进一步区分接下来的请求是要做什么
        boolean ok = true;
        if (request.getType() == 0x1) {
            // 表示创建一个channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] 创建channel完成！channelId = " + basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            // 表示销毁一个channel
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[BrokerServer] 销毁channel完成！channelId = " + basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            // 表示创建于一个交换机
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(),
                    arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
            System.out.println("[BrokerServer] 创建交换机完成！exchangeName = " + arguments.getExchangeName());
        } else if (request.getType() == 0x4) {
            // 表示删除交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
            System.out.println("[BrokerServer] 删除交换机完成！exchangeName = " + arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            // 表示创建队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable(), arguments.isExclusive(),
                    arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            // 表示销毁队列
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (request.getType() == 0x7) {
            // 表示创建绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getExchangeName(), arguments.getQueueName(), arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            // 删除绑定
            QueueUnBindArguments arguments = (QueueUnBindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getExchangeName(), arguments.getQueueName());
        } else if (request.getType() == 0x9) {
            // 发送消息
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(),
                    arguments.getBasicProperties(), arguments.getBody());
        } else if (request.getType() == 0xa) {
            // 订阅消息
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(),
                    new Consumer() {
                        @Override
                        public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                            // 1.根据consumerTag找到session对象
                            Socket socket = sessions.get(consumerTag);
                            if (socket == null || socket.isClosed()) {
                                throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭！");
                            }
                            // 2.构造响应数据
                            SubscribeReturns subscribeReturns = new SubscribeReturns();
                            subscribeReturns.setChannelId(consumerTag);
                            subscribeReturns.setRid("");
                            subscribeReturns.setBasicProperties(basicProperties);
                            subscribeReturns.setBody(body);
                            subscribeReturns.setOk(true);
                            byte[] payload = BinaryTool.toBytes(subscribeReturns);
                            Response response = new Response();
                            response.setType(0xc);
                            response.setLength(payload.length);
                            response.setPayload(payload);
                            // 3.将响应写回客户端
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream, response);
                        }
                    });
        } else if (request.getType() == 0xb) {
            // 调用basicAck确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());
        } else {
            throw new MqException("[BrokerServer] 未知的 type! type = " + request.getType());
        }
        // 3.构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] type = " + response.getType() + ",length = " + response.getLength()
            + ",rid = " + basicReturns.getRid() + ",channelId = " + basicReturns.getChannelId());
        return response;
    }

    // 将响应写回客户端
    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        dataOutputStream.flush();
    }

    private void clearClosedSession(Socket clientSocket) {
        // 清理已经关闭的socket
        List<String> toDeleteChannel = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == clientSocket) {
                // 不能一边删除一边遍历，先将socket对应的key存起来
                toDeleteChannel.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannel) {
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理session完毕！被清理的 channelId = " + toDeleteChannel);
    }
}
